//
//  ApplyRefundViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/9/17.
//  Copyright © 2020 王洋. All rights reserved.
//
#import "AFNetworking.h"

#import "CommonImageUploadCell.h"

#import "ApplyRefundSubmitModel.h"

#import "CommonRefundReasonModel.h"

#import "ApplyRefundViewController.h"

@interface ApplyRefundViewController ()<UICollectionViewDelegate, UICollectionViewDataSource,TZImagePickerControllerDelegate, UITextViewDelegate>

@property (nonatomic, strong) ApplyRefundSubmitModel *submitModel;

@property (nonatomic, strong) NSMutableArray <CommonRefundReasonModel *>* reasonArray;

@end

@implementation ApplyRefundViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self prepareData];
    [self initView];
    [self request_refundReason];
}

- (void)prepareData {
    
    self.submitModel.orderNo = self.paramModel.orderNo;

    self.submitModel.refundType = 1;
    self.submitModel.refundTypeId = 1;
    self.submitModel.refundStatus = 1;
    self.submitModel.userId = [TTUserModel sharedObject].userId;
    self.submitModel.sysMediaList = @[].mutableCopy;
    CommonMediaModel *mediaModel = [[CommonMediaModel alloc] init];
    mediaModel.url = @"";
    [self.submitModel.sysMediaList addObject:mediaModel];

    self.refundMoneyLab.text =[NSString stringWithFormat:@"¥%@",[Utilities changeDoubleToString:self.paramModel.payAmount]];
}

- (void)initView {
    
    self.title = @"申请退款";
    
    self.refundDescTV.delegate = self;
    
    UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.collectionview.collectionViewLayout = flowLayout;
    self.collectionview.delegate = self;
    self.collectionview.dataSource = self;
    self.collectionview.showsHorizontalScrollIndicator = NO;
    self.collectionview.showsVerticalScrollIndicator = NO;

    [self.collectionview registerNib:[UINib nibWithNibName:@"CommonImageUploadCell" bundle:nil] forCellWithReuseIdentifier:@"CommonImageUploadCellID"];
    self.collectionview.backgroundColor = [UIColor clearColor];
    
    WEAKSELF
    [self.selReasonControl addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
       
        [weakSelf selRefundReason];
    }];
    
}

- (void)textViewDidBeginEditing:(UITextView *)textView {
    
    if ([textView.text isEqualToString:@"请输入退款说明"]) {
        textView.text = @"";
    }
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.refundDescTV pp_clipCorners:UIRectCornerAllCorners radius:6];
        [self.handleBtn pp_clipCorners:UIRectCornerAllCorners radius:self.handleBtn.frame.size.height/2];
    });
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView {

    self.submitModel.remark = textView.text;
    return YES;
}

- (IBAction)handleAction:(id)sender {
    
    [self.view endEditing:YES];
    
    if (self.submitModel.refundReasonId.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请选择退款原因"];
        [SVProgressHUD dismissWithDelay:1];
        return;
    }
    
    if (self.submitModel.sysMediaList.count > 0 && self.submitModel.sysMediaList.firstObject.url.length > 0) {
    } else {
        [SVProgressHUD showErrorWithStatus:@"请上传凭证图片"];
        [SVProgressHUD dismissWithDelay:1];
        return;
    }
    
    if (self.submitModel.remark.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请填写退款具体说明"];
        [SVProgressHUD dismissWithDelay:1];
        return;
    }
    
    [self request_handleRefund];
}

- (void)selRefundReason {
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];

    for (int i = 0; i < self.reasonArray.count; i++) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:self.reasonArray[i].rgrReason
                                               style:UIAlertActionStyleDefault
                                             handler:^(UIAlertAction *action) {
                                                 // do something here
            
            for (CommonRefundReasonModel *model in self.reasonArray) {
                if ([model.rgrReason isEqualToString:action.title]) {
                    
                    self.submitModel.refundReasonId = model.rgrId;
                    self.submitModel.refundRemark = model.rgrReason;
                    self.refundReasonLab.text = model.rgrReason;
                }
            }
        }];
        
        [alertController addAction:action];
    }
    
    

    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消"
                                           style:UIAlertActionStyleCancel
                                         handler:^(UIAlertAction *action) {
                                             // do something here
                                         }];

    [alertController addAction:cancleAction];
    [alertController setModalPresentationStyle:UIModalPresentationPopover];
    [self presentViewController:alertController animated:YES completion:nil];
    
}

#pragma mark collectionview

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CommonImageUploadCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CommonImageUploadCellID" forIndexPath:indexPath];
    [cell fillCellWithModel:self.submitModel.sysMediaList[indexPath.row]];

    WEAKSELF
    cell.CommonImageUploadCellBlock = ^(CommonImageUploadCellActionType type) {
        
        switch (type) {
            case CommonImageUploadCellActionType_del:{
                
                [weakSelf delPhotoWithIndex:indexPath.row];
                
            } break;
            case CommonImageUploadCellActionType_tap:{
                
                [weakSelf uplodPhoto];
            } break;
            default:
                break;
        }
    };
    
    return cell;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.submitModel.sysMediaList.count;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    return CGSizeMake(100, 100);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

}

- (void)delPhotoWithIndex:(NSInteger)index {
    //删掉对应的
    [self.submitModel.sysMediaList removeObjectAtIndex:index];
    
    if (self.submitModel.sysMediaList.count == 0) {
        CommonMediaModel *imgModel = [[CommonMediaModel alloc] init];
        imgModel.url = @"";
        [self.submitModel.sysMediaList addObject:imgModel];
    }
    
    [self.collectionview reloadData];
}

- (void)delPhotoWithSection:(NSInteger)section AndIndex:(NSInteger)index {
    //删掉对应的
    [self.submitModel.sysMediaList removeObjectAtIndex:index];
    
    if (self.submitModel.sysMediaList.count == 0) {
        CommonMediaModel *imgModel = [[CommonMediaModel alloc] init];
        imgModel.url = @"";
        [self.submitModel.sysMediaList addObject:imgModel];
    }
    
    [self.collectionview reloadData];
}

- (void)uplodPhoto {

    NSInteger count = 3;
    TZImagePickerController *vc = [[TZImagePickerController alloc]
                                   initWithMaxImagesCount:count delegate:self];

    vc.naviBgColor = default_color_white;
    vc.naviTitleColor = default_color_black;
    vc.barItemTextColor = default_color_black;

    vc.photoWidth = 2048.0f;
    
    vc.preferredLanguage = @"zh-Hans";

    //筛选到只剩图片
    vc.allowPickingVideo = NO;
    vc.allowPickingMultipleVideo = NO;
    vc.allowPickingGif = NO;
    vc.allowPickingVideo = NO;

    vc.showSelectedIndex = YES;
    vc.showSelectBtn = YES;

    //裁剪
    vc.allowCrop = YES;
    vc.cropRect = CGRectMake( 0 ,(TTScreenHeight - TTScreenWidth)/2, TTScreenWidth, TTScreenWidth);

    WEAKSELF
    [vc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
        // 准备保存结果的数组，元素个数与上传的图片个数相同，先用 NSNull 占位
        NSMutableArray* result = [NSMutableArray array];
        for (int i = 0; i < photos.count; i++) {
            [result addObject:[NSNull null]];
        }
        
        dispatch_group_t group = dispatch_group_create();

        [SVProgressHUD showWithStatus:@"正在上传评价图片"];
        for (NSInteger i = 0; i < photos.count; i++)
        {
            dispatch_group_enter(group);
            dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                
                // ContentType设置
                AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
                manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"image/jpeg",@"image/png",@"application/octet-stream",@"text/json",nil];
                manager.requestSerializer= [AFHTTPRequestSerializer serializer];
                manager.responseSerializer= [AFHTTPResponseSerializer serializer];
                [manager.requestSerializer setValue:[TTUserModel sharedObject].token forHTTPHeaderField:@"token"];
                
                // 上传完整地址
                NSString * urlString = [NSString stringWithFormat:@"%@headImgUpload",TT_Global_Service_Domain];
                
                [manager POST:urlString parameters:nil headers:@{} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                            
                    if (photos[i] != nil) {
                    NSData *data = UIImageJPEGRepresentation(photos[i], 0.2f);
                    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                    formatter.dateFormat = @"yyyyMMddHHmmss";
                    NSString *str = [formatter stringFromDate:[NSDate date]];
                    NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
                    [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/jpg"];
                    }
                    
                } progress:^(NSProgress * _Nonnull uploadProgress) {
                    NSLog(@"%.2f",uploadProgress.fractionCompleted);

                } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

                    NSString *resultStr = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];

                    if ([resultStr isKindOfClass:[NSString class]]) {
                        
                        @synchronized (result) {
                            result[i] = resultStr;
                        }
                    }
                    dispatch_group_leave(group);
                    
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    dispatch_group_leave(group);

                }];
            });
           
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue(), ^{
            NSLog(@"上传完成!");
            [SVProgressHUD showSuccessWithStatus:@"上传成功"];
            [SVProgressHUD dismissWithDelay:0.5];

            self.submitModel.sysMediaList = @[].mutableCopy;
            for (int i = 0; i < result.count; i++) {
                NSString *imgStr = result[i];

                if ([imgStr isKindOfClass:[NSString class]]) {
                    
                    CommonMediaModel *model = [[CommonMediaModel alloc] init];
                    model.url = imgStr;
                    [weakSelf.submitModel.sysMediaList addObject:model];
                    [weakSelf.collectionview reloadData];
                }
            }
        });
    }];

    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:vc animated:YES completion:nil];
}

- (ApplyRefundSubmitModel *)submitModel {
    if (!_submitModel) {
        _submitModel = [[ApplyRefundSubmitModel alloc] init];
    }
    return _submitModel;
}

- (NSMutableArray<CommonRefundReasonModel *> *)reasonArray {
    
    if (!_reasonArray) {
        _reasonArray = @[].mutableCopy;
    }
    return _reasonArray;
}

- (void)request_refundReason {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_RefundReason];

    self.handleBtn.userInteractionEnabled = NO;
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        weakSelf.handleBtn.userInteractionEnabled = YES;

        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {

                NSArray *resultArray = [data valueForKey:@"data"];
//                NSArray *reasonArray = []
                weakSelf.reasonArray = @[].mutableCopy;
                if ([resultArray isKindOfClass:[NSArray class]]) {
                    
                    for (int i = 0; i < resultArray.count; i++) {
                        NSDictionary *arrayDic = resultArray[i];
                        
                        CommonRefundReasonModel *model = [CommonRefundReasonModel modelWithDictionary:arrayDic];
                        [weakSelf.reasonArray addObject:model];
                    }
                }

            } else {

            }
        }

    } FailedBlock:^(NSError * _Nonnull error) {
        weakSelf.handleBtn.userInteractionEnabled = YES;

    }];
}

- (void)request_handleRefund {
    
    self.handleBtn.userInteractionEnabled = NO;
    NSMutableDictionary *dic = @{}.mutableCopy;
    dic = [self.submitModel modelToJSONObject];

    NSMutableArray *imageUrls = @[].mutableCopy;
    for (int i = 0; i < self.submitModel.sysMediaList.count; i++) {
        
        CommonMediaModel *mediaModel = self.submitModel.sysMediaList[i];
        NSMutableDictionary *mediaDic = [mediaModel modelToJSONObject];

        [imageUrls addObject:mediaDic];
    }
    [dic setValue:imageUrls forKey:@"sysMediaList"];
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_ApplyRefund];

    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        weakSelf.handleBtn.userInteractionEnabled = YES;

        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {

                [SVProgressHUD showSuccessWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
                [weakSelf.navigationController popToRootViewControllerAnimated:NO];
            } else {

                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }

    } FailedBlock:^(NSError * _Nonnull error) {
        weakSelf.handleBtn.userInteractionEnabled = YES;

    }];    
}

@end
